/**
 * Created by Admin on 2017/7/18.
 */
var merchant = {
    merchantInfo: JSON.parse(sessionStorage['merchant']),
    roleList: null,
    init: function () {
        $("#merchant-name").html(this.merchantInfo.merchant_info.name);
        this.getRoles();
        this.getUserInfoList();
    },
    getRoles: function () {
        var data = JSON.stringify({token: this.merchantInfo.token});
        var that = this;
        httpReq("system/get_all_roles", data, function (res) {
            that.roleList = res.records;
            for (var i = 0, html = '', label = ''; i < that.roleList.length; i++) {
                label += '<label class="checkbox-label"><input name="roles" type="checkbox" value="' + that.roleList[i].id + '" onclick="isChecked(this)"/> ' + that.roleList[i].name + '</label>';
            }
            html += '<label  class="control-label">Roles：</label>' + label + '<span class="help-block"></span>';
            $("#roles").html(html);
            $(".checkbox-label:contains(Merchant_Clerk)").children().click(function () {
                if (this.checked) {
                    var orgList = that.merchantInfo.merchant_info.organizations;
                    for (var i = 0, html = '', label = ''; i < orgList.length; i++) {
                        label += '<label class="radio-label"><input name="organization_id" type="radio" value="' + orgList[i].id + '"/> ' + orgList[i].name + '</label>';
                    }
                    html += '<label  class="control-label">Organizations：</label>' + label + '';
                    $("#organizations").html(html);
                } else {
                    $("#organizations").html('');
                }
            });
        })
    },
    getUserInfoList: function () {
        var that = this;
        var merchantRoles = that.merchantInfo.roles;
        var data = JSON.stringify({token: that.merchantInfo.token, merchant_no: that.merchantInfo.merchant_no});
        var org = that.merchantInfo.merchant_info.organizations;
        for (var k in merchantRoles) {
            if (merchantRoles[k].name == "Merchant_Admin") {
                loading.show();
                httpReq("system/get_userinfo_list_of_merchant", data, function (res) {
                    if (res.return_code == "SUCCESS") {
                        loading.hidden();
                        var users = res.records;
                        var roles = that.roleList;
                        for (var i = 0, html = '', html2 = '', html3 = ''; i < users.length; i++) {
                            for (var jj = 0; jj < users[i].roles.length; jj++) {
                                var userId = users[i].roles[jj];
                                for (var z = 0; z < roles.length; z++) {
                                    if (roles[z].id == userId) {
                                        html3 += '<p class="role-list-item">' + roles[z].name + '</p>';
                                    }
                                }
                            }
                            for (var ii = 0; ii < users[i].organizations.length; ii++) {
                                var orgId = users[i].organizations[ii];
                                for (var j = 0; j < org.length; j++) {
                                    if (org[j].id == orgId) {
                                        html2 += '<p class="org-list-item">' + org[j].name + '</p>';
                                    }
                                }
                            }

                            html += '<li class="user-list-item"><div class="userInfo"><div class="flex flex-between"><h3 class="name">' + users[i].username + '</h3><button type="button" class="delete-btn" data-id="' + users[i].user_id + '" onclick="merchant.deleteUser(this)">Delete</button></div></div><div class="user-roles"><h4 class="user-title">Roles</h4><div class="role-list">' + html3 + '</div></div><div class="user-org"><h4 class="user-title">Organizations</h4><div class="org-list">' + html2 + '</div></div></li>';
                            html2 = html3 = '';
                        }
                        $("#user-list").html(html);
                        var userName = $(".name");
                        for (var b = 0; b < userName.length; b++) {
                            if ($(userName[b]).text() == that.merchantInfo.username) {
                                $(userName[b]).next().remove();
                            }
                        }
                        var roleContainer = $(".role-list-item");
                        for (var m = 0; m < roleContainer.length; m++) {
                            if ($(roleContainer[m]).text() != "Merchant_Clerk" && $(roleContainer[m]).siblings().text() != "Merchant_Clerk") {
                                $(roleContainer[m]).parent().parent().next().remove();
                            }
                        }
                    } else {
                        swal({
                            title: "Error",
                            text: "System error!",
                            type: "error",
                            animation: "slide-from-top"
                        });
                    }
                }, function (err) {
                    if ($("#myLoading")) {
                        loading.hidden();
                    }
                    err.responseText = JSON.parse(err.responseText);
                    swal({
                        title: "Error",
                        text: err.responseText.error_msg,
                        type: "error",
                        animation: "slide-from-top"
                    });
                })
            } else {
                var html = '<li style="text-align:center">You have successfully bond to this account.</li>';
                $("#user-list").html(html);
            }
        }
    },
    addUser: function () {
        var token = this.merchantInfo.token;
        var merchant_no = this.merchantInfo.merchant_no;
        var rolesCheckBox = $("input[name='roles']");
        var rolesId = [];
        var name = false, pwd = false, phone = false, email = false, roles = false, repeat = false;
        if ($("#name").val() == "") {
            $("#name").next().addClass('block').html("The user name cannot be empty");
            name = false;
        } else {
            name = true;
        }
        if ($("#pwd").val() == "") {
            $("#pwd").next().addClass('block').html("The password cannot be empty");
            pwd = false;
        } else {
            pwd = true;
        }
        if ($("#phone").val() == "") {
            $("#phone").next().addClass('block').html("The phone cannot be empty");
            phone = false;
        } else {
            phone = true;
        }
        if ($("#email").val() == "") {
            $("#email").next().addClass('block').html("The email cannot be empty");
            email = false;
        } else {
            email = true;
        }
        if ($("#rePwd").val() == "") {
            $("#email").next().addClass('block').html("The email cannot be empty");
            repeat = false;
        } else if ($("#rePwd").val() != $("#pwd").val()) {
            $("#rePwd").next().addClass('block').html("The two passwords entered are not consistent");
            repeat = false;
        } else {
            repeat = true;
        }
        if ($("input:checkbox[name='roles']:checked").length > 0) {
            roles = true;
        } else {
            $("#roles").children('.help-block').addClass('block').html('Please select at least one role')
        }
        if (name && pwd && phone && email && roles && repeat) {
            var data = {};
            var str = $("#userInfo").serialize();
            str = decodeURIComponent(str, true);
            str = str.split("&");
            for (var i = 0, arr; i < str.length; i++) {
                arr = str[i].split("=");
                data[arr[0]] = arr[1];
            }
            for (var k in rolesCheckBox) {
                if (rolesCheckBox[k].checked) {
                    rolesId.push(rolesCheckBox[k].value);
                }
            }
            data.token = token;
            data.merchant_no = merchant_no;
            data.roles = rolesId;
            if (data.organization_id == undefined) {
                delete data.organization_id;
            }
            data = JSON.stringify(data);
            loading.show();
            httpReq("system/add_user", data, function (res) {
                loading.hidden();
                if (res.return_code == "SUCCESS") {
                    swal({
                        title: "Success",
                        text: "User added success",
                        type: "success",
                        animation: "slide-from-top"
                    }, function (isConfirm) {
                        if (isConfirm) {
                            window.location.reload();
                        }
                    });
                }
            }, function (err) {
                loading.hidden();
                err.responseText = JSON.parse(err.responseText);
                swal({
                    title: "Error",
                    text: err.responseText.error_msg,
                    type: "error",
                    animation: "slide-from-top"
                });
            })
        }
    },
    deleteUser: function (el) {
        loading.show();
        var that = this;
        var id = $(el).attr("data-id");
        var data = JSON.stringify({
            token: that.merchantInfo.token,
            merchant_no: that.merchantInfo.merchant_no,
            user_id: id
        });
        httpReq("system/remove_user", data, function (res) {
            loading.hidden();
            if (res.return_code == "SUCCESS") {
                swal({
                    title: "Success",
                    text: "User deletion success",
                    type: "success",
                    animation: "slide-from-top"
                }, function (isConfirm) {
                    if (isConfirm) {
                        window.location.reload();
                    }
                });
            }
        }, function (err) {
            loading.hidden();
            err.responseText = JSON.parse(err.responseText);
            swal({
                title: "Error",
                text: err.responseText.error_msg,
                type: "error",
                animation: "slide-from-top"
            });
        })
    },
};
merchant.init();

function showModal() {
    $("[data-toggle = 'modal']").click(function () {
        var id = $(this).attr("data-id");
        $(id).addClass("block");
        $("body").addClass("no-scroll");
        $("html").addClass("no-scroll");
    })
}
showModal();

function closeModal() {
    $(".modal .flex").click(function () {
        $(this).parent().removeClass("block");
        $("body").removeClass("no-scroll");
        $("html").removeClass("no-scroll");
    });

    $(".close").click(function () {
        $(this).parents(".modal").removeClass("block");
        $("body").removeClass("no-scroll");
        $("html").removeClass("no-scroll");
    });
}
closeModal();

$(".modal-content").click(function (e) {
    e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;
});

function removeHelp(el) {
    if ($(el).val() !== "") {
        $(el).next().removeClass("block")
    }
}

function isChecked(el) {
    if ($(el).is(':checked')) {
        $("#roles").children('.help-block').removeClass('block');
    }
}

